<template>
  <el-button 
    type="danger" 
    size="small" 
    @click="handleAddToBlacklist"
    :disabled="isInBlacklist || loading"
  >
    {{ isInBlacklist ? '已在黑名单' : '加入黑名单' }}
  </el-button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addToBlacklist, checkUserInBlacklist } from '@/api/admin/blackUser'

const props = defineProps({
  userId: {
    type: Number,
    required: true
  },
  userName: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['success'])

const loading = ref(false)
const isInBlacklist = ref(false)

// 检查用户是否在黑名单中
const checkBlacklistStatus = async () => {
  try {
    const res = await checkUserInBlacklist(props.userId)
    if (res.code === 200) {
      isInBlacklist.value = res.data
    }
  } catch (error) {
    console.error('检查黑名单状态失败:', error)
  }
}

// 加入黑名单
const handleAddToBlacklist = () => {
  ElMessageBox.confirm(
    `确认将用户 ${props.userName || props.userId} 加入黑名单吗？加入后该用户将被禁止登录系统。`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true
    try {
      const res = await addToBlacklist(props.userId)
      if (res.code === 200) {
        ElMessage.success('加入黑名单成功')
        isInBlacklist.value = true
        emit('success')
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (error) {
      console.error('加入黑名单失败:', error)
      ElMessage.error('加入黑名单失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

onMounted(() => {
  checkBlacklistStatus()
})
</script> 